<script setup>
import { ref } from 'vue';
import { ElMessage, ElImageViewer } from 'element-plus';
import { Picture, UploadFilled, ZoomIn } from '@element-plus/icons-vue';
import { uploadToQiniu } from '@/utils/qiniu';

const props = defineProps({
  maxSize: {
    type: Number,
    default: 5 * 1024 * 1024 // 默认5MB
  },
  value: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['upload-success', 'update:value']);

const coverUrl = ref(props.value || '');
const uploadProgress = ref(0);
const isUploading = ref(false);
const fileInputRef = ref(null);
// 图片预览相关状态
const showViewer = ref(false);

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 文件类型检查
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }

  // 文件大小检查
  if (file.size > props.maxSize) {
    const maxSizeMB = props.maxSize / (1024 * 1024);
    ElMessage.error(`图片大小不能超过 ${maxSizeMB}MB`);
    return;
  }

  // 开始上传
  isUploading.value = true;
  uploadProgress.value = 0;

  try {
    // 调用新的七牛云上传工具
    const result = await uploadToQiniu(file, 'cover', (percent) => {
      // 更新上传进度
      uploadProgress.value = Math.min(percent, 100);
    });

    // 上传成功，更新图片URL
    coverUrl.value = result.url;
    emit('upload-success', result.url);
    emit('update:value', result.url);
    isUploading.value = false;
    ElMessage.success('封面上传成功');

  } catch (error) {
    isUploading.value = false;
    uploadProgress.value = 0;
    ElMessage.error('封面上传失败，请重试');
    console.error('封面上传失败:', error);
  } finally {
    // 重置文件输入框，允许重新选择相同文件
    if (fileInputRef.value) {
      fileInputRef.value.value = '';
    }
  }
};

// 取消上传 - 由于新API不支持取消，此功能可能不再可用
const cancelUpload = () => {
  isUploading.value = false;
  uploadProgress.value = 0;
  ElMessage.info('已取消上传');

  // 重置文件输入框
  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }
};

// 重新上传
const reupload = () => {
  coverUrl.value = '';
  emit('upload-success', '');
  emit('update:value', '');

  // 重置文件输入，允许重新选择相同文件
  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }
};

// 触发文件选择对话框
const triggerFileInput = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click();
  }
};

// 显示图片预览器
const showImageViewer = () => {
  showViewer.value = true;
};

// 关闭图片预览器
const closeViewer = () => {
  showViewer.value = false;
};

// 监听拖拽事件
const handleDragOver = (e) => {
  e.preventDefault();
  e.stopPropagation();
};

const handleDrop = (e) => {
  e.preventDefault();
  e.stopPropagation();

  if (isUploading.value) return;

  const files = e.dataTransfer.files;
  if (files.length > 0) {
    // 模拟文件选择事件
    handleFileChange({ target: { files } });
  }
};

// 暴露方法给父组件
defineExpose({
  reupload
});
</script>

<template>
  <div class="uploader-container">
    <div class="uploader-title">封面上传</div>

    <!-- 上传前的状态 -->
    <div v-if="!coverUrl && !isUploading" class="upload-area" @click="triggerFileInput" @dragover="handleDragOver"
      @drop="handleDrop">
      <el-icon class="upload-icon">
        <Picture />
      </el-icon>
      <div class="upload-tip">点击或拖拽图片文件到此区域</div>
      <div class="upload-sub-tip">支持 JPG、PNG 格式</div>
      <input ref="fileInputRef" type="file" class="file-input" accept="image/jpeg,image/png,image/jpg"
        @change="handleFileChange">
    </div>

    <!-- 上传中的状态 -->
    <div v-else-if="isUploading" class="uploading-area">
      <div class="progress-info">
        <div class="progress-text">上传中... {{ Math.round(uploadProgress) }}%</div>
        <el-progress type="circle" :percentage="Math.floor(uploadProgress)"
          :status="uploadProgress < 100 ? 'primary' : 'success'" />
      </div>
      <el-button @click="cancelUpload" type="danger" plain>取消上传</el-button>
    </div>

    <!-- 上传成功的状态 -->
    <div v-else class="success-area">
      <el-icon class="success-icon">
        <SuccessFilled />
      </el-icon>
      <div class="success-message">图片上传成功</div>
      <div class="success-submessage">视频将在提交发布后显示</div>
      <div style="display: flex; justify-content: space-between;">
        <el-button @click="showImageViewer" type="primary">点击预览</el-button>
        <el-button @click="reupload" type="info" plain>重新上传</el-button>
      </div>
    </div>

    <!-- 图片预览器 -->
    <el-image-viewer v-if="showViewer" :url-list="[coverUrl]" :hide-on-click-modal="true" @close="closeViewer" />
  </div>
</template>


<style scoped lang="scss">
.uploader-container {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  height: 320px;
  display: flex;
  flex-direction: column;
  background-color: white;
}

.uploader-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.upload-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;

  &:hover {
    border-color: #1890ff;

    .upload-icon {
      color: #1890ff;
    }

    .upload-tip {
      color: #1890ff;
    }
  }
}

.upload-icon {
  font-size: 48px;
  color: #999;
  margin-bottom: 16px;
  transition: color 0.3s;
}

.upload-tip {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  transition: color 0.3s;
}

.upload-sub-tip {
  font-size: 12px;
  color: #999;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
  pointer-events: none;
}

.uploading-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.progress-info {
  text-align: center;
}

.progress-text {
  margin-bottom: 16px;
  font-size: 16px;
  color: #666;
}

.cover-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.upload-success-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  color: #67c23a;
  font-weight: 500;

  .success-icon {
    margin-right: 5px;
    font-size: 20px;
  }

  .success-text {
    font-size: 16px;
  }
}

.image-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  border-radius: 4px;
  height: calc(100% - 80px);
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  margin-bottom: 10px;
  border: 1px solid #e0e0e0;
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-image {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  object-fit: contain;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.cover-actions {
  margin-top: 8px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 新的上传成功区域样式 */
.success-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f6f9ff;
  border-radius: 6px;
  border: 1px solid #e6f0fe;
}

.success-icon {
  font-size: 60px;
  color: #67c23a;
  margin-bottom: 16px;
}

.success-message {
  font-size: 18px;
  font-weight: 500;
  color: #67c23a;
  margin-bottom: 8px;
}

.success-submessage {
  font-size: 14px;
  color: #909399;
  margin-bottom: 24px;
}

.reupload-btn {
  margin-top: 8px;
}

/* 自定义 el-image-viewer 组件样式 */
:deep(.el-image-viewer__wrapper) {
  z-index: 2100;
}

:deep(.el-image-viewer__img) {
  max-width: 90vw;
  max-height: 90vh;
}
</style>